import pandas as pd
from datetime import datetime
from typing import Union 

class live_data:
    def __init__(
        self,
    ):
        self.superchat = {}
        self.guard = {}
        self.gift = {}
        self.manghe = {}

    def _add_record(self, storage, user, **fields):
        if user not in storage:
            storage[user] = []
        storage[user].append(fields)

    def get_superchat(self):
        return self.superchat

    def get_guard(self):
        return self.guard

    def get_gift(self):
        return self.gift

    def get_manghe(self):
        return self.manghe

    def recieve_superchat(self, user: str, coin: Union[int, float], message: str, time: int):
        self._add_record(self.superchat, user,
                        coin=coin, message=message, time=datetime.fromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S'))
        # print(self.superchat)

    def recieve_guard(self, user: str, type: str, num: str, coin: Union[int, float], 
                    show_message: str, time: int):
        self._add_record(self.guard, user,
                        type=type, num=num, coin=coin, 
                        show_message=show_message, time=datetime.fromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S'))
        # print(self.guard)

    def recieve_gift(self, user: str, num: int, gift: str, coin: Union[int, float], time: int):
        self._add_record(self.gift, user, num=num,
                        gift=gift, coin=coin, time=datetime.fromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S'))
        print(self.gift)

    def recieve_manghe(self, user: str, num: int,  original_gift: str, original_coin: Union[int, float],
                    real_gift: str, real_coin: Union[int, float], time: int):
        self._add_record(self.manghe, user, num=num,
                        original_gift=original_gift, original_coin=original_coin,
                        real_gift=real_gift, real_coin=real_coin, time=datetime.fromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S'))    
        print(self.manghe)

    async def _transfer_data(self, data, columns_mapping):
        records = []
        for user, items in data.items():
            for item in items:
                record = {'用户名': user}
                record.update({col: item[key] for col, key in columns_mapping.items()})
                records.append(record)
        return pd.DataFrame(records)

    async def transfer_superchat(self):
        df = await self._transfer_data(self.superchat,
                        {'金额': 'coin', '消息内容': 'message', '时间': 'time'})
        self.superchat.clear()
        return df

    async def transfer_guard(self):
        df = await self._transfer_data(self.guard,
                        {'上舰类型': 'type', '数量': 'num', '金额': 'coin', 
                            '提示消息': 'show_message', '时间': 'time'})
        self.guard.clear()
        return df

    async def transfer_gift(self):
        try:
            print(self.gift)
            df = await self._transfer_data(self.gift,
                        {   '数量'    : 'num',
                            '礼物（不包含盲盒）': 'gift', 
                            '金额': 'coin', '时间': 'time'})
            self.gift.clear()
            print(df)
            return df
        except Exception as e:
            print(f"处理礼物数据出错: {str(e)}")
            raise

    async def transfer_manghe(self):
        df = await self._transfer_data(self.manghe,
                        {   '数量'    : 'num',
                            '盲盒类型': 'original_gift',
                            '盲盒金额': 'original_coin',
                            '爆出礼物': 'real_gift',
                            '实际金额': 'real_coin',
                            '时间': 'time'})
        self.manghe.clear()
        return df
